package com.sxj.corejava.code13_JDBC;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Test05_分页查询 {

    public static void main(String[] args) {
        // 查询第二页数据,每页3条
        List<User> users = selectPage(2, 3);
        for (User user : users) {
            System.out.println(user);
        }
        System.out.println("************************************");
        // 查询第4页数据,每页2条
        users = selectPage(4, 2);
        for (User user : users) {
            System.out.println(user);
        }
    }

    public static List<User> selectPage(Integer pageNo, Integer pageSize) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" limit ?,?")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, (pageNo - 1) * pageSize);
            ps.setInt(2, pageSize);
            rs = ps.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                users.add(user);
            }
        } catch (DataAccessException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return users;
    }

}
